"""
Pydantic模型定义 - 用于API请求和响应
"""
from datetime import datetime
from typing import Optional, List, Dict, Any
from pydantic import BaseModel, EmailStr, Field, validator
from enum import Enum


class UserRole(str, Enum):
    """用户角色枚举"""
    ADMIN = "admin"
    USER = "user"


class TaskStatus(str, Enum):
    """任务状态枚举"""
    PENDING = "pending"
    PROCESSING = "processing"
    COMPLETED = "completed"
    FAILED = "failed"


class ExecutionMode(str, Enum):
    """执行模式枚举"""
    SYNC = "sync"
    ASYNC = "async"


class ContentType(str, Enum):
    """内容类型枚举"""
    TEXT = "text"
    MARKDOWN = "markdown"
    LAYOUT = "layout"
    IMAGES = "images"


class SliceStrategy(str, Enum):
    """切片策略枚举"""
    SEMANTIC = "semantic"
    PARAGRAPH = "paragraph"
    FIXED = "fixed"


# 用户相关模型
class UserBase(BaseModel):
    """用户基础模型"""
    username: str = Field(..., min_length=3, max_length=50)
    email: EmailStr
    role: UserRole = UserRole.USER


class UserCreate(UserBase):
    """创建用户模型"""
    password: str = Field(..., min_length=6)


class UserUpdate(BaseModel):
    """更新用户模型"""
    username: Optional[str] = Field(None, min_length=3, max_length=50)
    email: Optional[EmailStr] = None
    role: Optional[UserRole] = None
    is_active: Optional[bool] = None


class UserResponse(UserBase):
    """用户响应模型"""
    id: int
    created_at: datetime
    updated_at: datetime
    is_active: bool
    last_login: Optional[datetime]
    
    class Config:
        from_attributes = True


class UserLogin(BaseModel):
    """用户登录模型"""
    username: str
    password: str
    client_hash: Optional[bool] = False


class Token(BaseModel):
    """Token模型"""
    access_token: str
    token_type: str
    expires_in: int
    user: UserResponse


# 解析任务相关模型
class ParseOptions(BaseModel):
    """解析选项模型"""
    output_format: str = "all"  # all, text, markdown, layout, images
    language: str = "auto"  # auto, zh, en, mixed
    ocr_engine: str = "paddle"  # paddle, tesseract, rapid
    extract_images: bool = True
    extract_tables: bool = True
    preserve_layout: bool = True


class ParseTaskCreate(BaseModel):
    """创建解析任务模型"""
    execution_mode: ExecutionMode = ExecutionMode.ASYNC
    parse_options: Optional[ParseOptions] = None
    priority: int = Field(5, ge=1, le=9, description="任务优先级，1为最高，9为最低")


class ParseTaskResponse(BaseModel):
    """解析任务响应模型"""
    id: int
    task_id: str
    user_id: int
    filename: str
    file_size: int
    status: TaskStatus
    progress: int
    created_at: datetime
    started_at: Optional[datetime]
    completed_at: Optional[datetime]
    error_message: Optional[str]
    execution_mode: ExecutionMode
    parse_options: Optional[Dict[str, Any]]
    priority: int
    
    class Config:
        from_attributes = True


class ParseResultResponse(BaseModel):
    """解析结果响应模型"""
    id: int
    task_id: int
    content_type: ContentType
    file_size: Optional[int]
    created_at: datetime
    metadata: Optional[Dict[str, Any]]
    
    class Config:
        from_attributes = True


class ParseCompleteResponse(BaseModel):
    """完整解析响应模型"""
    task_id: str
    status: TaskStatus
    results: Optional[Dict[str, Any]]
    download_urls: Optional[Dict[str, str]]


# 文档切片相关模型
class SliceOptions(BaseModel):
    """切片选项模型"""
    strategy: SliceStrategy = SliceStrategy.SEMANTIC
    chunk_size: int = Field(1000, gt=0, le=10000)
    overlap: int = Field(200, ge=0, le=1000)
    min_chunk_size: int = Field(100, gt=0)
    preserve_structure: bool = True
    extract_tables: bool = True
    process_images: bool = True


class SliceTaskCreate(BaseModel):
    """创建切片任务模型"""
    parse_task_id: int
    options: SliceOptions


class SliceTaskResponse(BaseModel):
    """切片任务响应模型"""
    id: int
    slice_id: str
    parse_task_id: int
    status: TaskStatus
    strategy: SliceStrategy
    chunk_size: int
    overlap: int
    total_chunks: int
    created_at: datetime
    completed_at: Optional[datetime]
    
    class Config:
        from_attributes = True


class SliceChunkResponse(BaseModel):
    """切片块响应模型"""
    id: int
    chunk_id: str
    text_content: str
    word_count: int
    page_number: Optional[int]
    position_info: Optional[Dict[str, Any]]
    metadata: Optional[Dict[str, Any]]
    created_at: datetime
    
    class Config:
        from_attributes = True


class SliceCompleteResponse(BaseModel):
    """完整切片响应模型"""
    slice_id: str
    status: TaskStatus
    chunks: List[SliceChunkResponse]
    total_chunks: int
    download_url: Optional[str]


# 系统管理相关模型
class SystemConfigCreate(BaseModel):
    """创建系统配置模型"""
    config_key: str = Field(..., min_length=1, max_length=100)
    config_value: str
    description: Optional[str] = None


class SystemConfigResponse(BaseModel):
    """系统配置响应模型"""
    id: int
    config_key: str
    config_value: str
    description: Optional[str]
    created_at: datetime
    updated_at: datetime
    
    class Config:
        from_attributes = True


class APILogResponse(BaseModel):
    """API日志响应模型"""
    id: int
    user_id: Optional[int]
    endpoint: str
    method: str
    status_code: Optional[int]
    response_time: Optional[float]
    ip_address: Optional[str]
    user_agent: Optional[str]
    created_at: datetime
    
    class Config:
        from_attributes = True


# 通用响应模型
class BaseResponse(BaseModel):
    """基础响应模型"""
    success: bool
    message: str
    data: Optional[Any] = None


class PaginatedResponse(BaseModel):
    """分页响应模型"""
    items: List[Any]
    total: int
    page: int
    limit: int
    pages: int
    stats: Optional[Dict[str, Any]] = None


class LogStatsResponse(BaseModel):
    """日志统计响应模型"""
    total_requests: int
    success_rate: float
    avg_response_time: Optional[float]
    error_count: int
    
    class Config:
        from_attributes = True


class HealthResponse(BaseModel):
    """健康检查响应模型"""
    status: str
    timestamp: datetime
    version: str
    database: str
    services: Dict[str, str]